YAHOO.namespace("card.paid");
YAHOO.namespace("card.paid.generate");

var Dom = YAHOO.util.Dom,
    Event = YAHOO.util.Event;


YAHOO.card.paid.generate.init = function () {
    var number_per_page_default = 8;
    var myPaginator = new YAHOO.widget.Paginator({
        containers: ['card-job-list-paging'],
        rowsPerPage: number_per_page_default,
        firstPageLinkLabel: '首页',
        previousPageLinkLabel: '上一页',
        nextPageLinkLabel: '下一页',
        lastPageLinkLabel: '末页'
    });
    var tableConfig = {
        paginator: myPaginator,
        MSG_EMPTY: '没有记录',
        dynamicData: true,
        initialLoad: false
    };

    var periodFormatter = function (elCell, oRecord) {
        if (oRecord.getData('periodType') == 'Y') {
            elCell.innerHTML = oRecord.getData('cardValidityPeriod') + "年";
        } else if (oRecord.getData('periodType') == 'M') {
            elCell.innerHTML = oRecord.getData('cardValidityPeriod') + "月";
        } else if (oRecord.getData('periodType') == 'D') {
            elCell.innerHTML = oRecord.getData('cardValidityPeriod') + "日";
        } else {
            elCell.innerHTML = "";
        }
    };
    var cardTypeFormatter = function (elCell, oRecord) {
        if (oRecord.getData('cardType').toLowerCase() == 'paid') {
            elCell.innerHTML = "销售卡";
        } else if (oRecord.getData('cardType').toLowerCase() == 'activity') {
            elCell.innerHTML = "活动卡";
        } else if (oRecord.getData('cardType').toLowerCase() == 'customize') {
            elCell.innerHTML = "定制卡";
        }else if (oRecord.getData('cardType').toLowerCase() == 'gift') {
            elCell.innerHTML = "赠送卡";
        }else {
            elCell.innerHTML = "";
        }
    };


    var columnDefs = [
        {key: "id", label: '批次号'},
        {key: "cardType", label: '卡类型',formatter:cardTypeFormatter},
        {key: "cardQuantity", label: '数量'},
        {key: "cardParValue", label: '星币值'},
        {key: "cardActivationDeadline", label: '截止日期'},
        {key: "period", label: '有效期', formatter: periodFormatter},
        {key: "dateAdded", label: '任务执行时间'},
        {key: "description", label: '备注'},
        {key: "updateBy", label: '最后更新者'},
        {  label: '星卡详情', className: "table-action", action: 'viewCards', formatter: function (elCell, oRecord) {
                elCell.innerHTML = '<a target="_blank" href="/ozing/cards?batchId=' + oRecord.getData('id') +  '#cardTable=batchId%3D' +  + oRecord.getData('id') + '">'+
                    '<img src="/static/images/preview.gif" title="详情" /></a>';
            }
        },
        {  label: 'Job详情', className: "table-action", action: 'viewJob', formatter: function (elCell, oRecord) {
            elCell.innerHTML = '<a target="_blank" href="/jobs/executions/' + oRecord.getData('executionId') + '">'+
                '<img src="/static/images/preview.gif" title="详情" /></a>';
        }
        }

    ];
    var cardsDataSource = new YAHOO.util.DataSource('/ozing/card/jobs.json?');
    cardsDataSource.responseType = YAHOO.util.DataSource.TYPE_JSON;
    cardsDataSource.responseSchema = {
        resultsList: 'records',
        fields: ['id', 'cardType', 'cardQuantity', 'cardParValue', 'cardActivationDeadline', 'cardValidityPeriod', 'periodType',
            'executionId', 'instanceId', 'batchStartTime', 'batchEndTime', 'status', 'description', 'dateAdded', 'updateBy'],
        metaFields:{
            totalRecords:'totalRecords',
            paginationRecordOffset:"startIndex",
            paginationRowsPerPage:"pageSize",
            sortKey: "sort",
            sortDir: "dir"
        }
    };
    var cardsDataTable = new YAHOO.widget.DataTable("card-job-list-table", columnDefs, cardsDataSource, tableConfig);

    cardsDataTable.showTableMessage(cardsDataTable.get("MSG_LOADING"), YAHOO.widget.DataTable.CLASS_LOADING);

    // Add the instances to the YAHOO.example namespace for inspection
    YAHOO.pingmob.BHMIntegration_files = {
        myPaginator  : myPaginator,
        cardsDataSource : cardsDataSource,
        cardsDataTable  : cardsDataTable
    };

    // Integrate with Browser History Manager
    var History = YAHOO.util.History;

    // Define a custom function to route sorting through the Browser History Manager
    var handleSorting = function (oColumn) {
        // Calculate next sort direction for given Column
        var sDir = this.getColumnSortDir(oColumn);

        // The next state will reflect the new sort values
        // while preserving existing pagination rows-per-page
        // As a best practice, a new sort will reset to page 0
        var newState = generateRequest(0, oColumn.key, sDir, this.get("paginator").getRowsPerPage());

        // Pass the state along to the Browser History Manager
        History.navigate("cardTable", newState);
    };
    cardsDataTable.sortColumn = handleSorting;

    // Define a custom function to route pagination through the Browser History Manager
    var handlePagination = function (state) {
        // The next state will reflect the new pagination values
        // while preserving existing sort values
        // Note that the sort direction needs to be converted from DataTable format to server value
        var sortedBy  = this.get("sortedBy"),
            newState = generateRequest(
                state.recordOffset, sortedBy.key, sortedBy.dir, state.rowsPerPage
            );

        // Pass the state along to the Browser History Manager
        History.navigate("cardTable", newState);
    };

    // First we must unhook the built-in mechanism...
    myPaginator.unsubscribe("changeRequest", cardsDataTable.onPaginatorChangeRequest);
    // ...then we hook up our custom function
    myPaginator.subscribe("changeRequest", handlePagination, cardsDataTable, true);

    // Update totalRecords on the fly with values from server
    cardsDataTable.doBeforeLoadData = function (oRequest, oResponse, oPayload) {
        var meta = oResponse.meta;
        oPayload.totalRecords = meta.totalRecords || oPayload.totalRecords;
        oPayload.pagination = {
            rowsPerPage:meta.paginationRowsPerPage || number_per_page_default,
            recordOffset:meta.paginationRecordOffset || 0
        };
        if(oPayload.totalRecords==undefined){
            oPayload.totalRecords=0;
        }
        oPayload.sortedBy = {
            key: meta.sortKey || "id",
            dir: (meta.sortDir) ? "yui-dt-" + meta.sortDir : "yui-dt-asc" // Convert from server value to DataTable format
        };
        return true;
    };

    var generateRequest = function (startIndex,sortKey,dir,results) {
        startIndex = startIndex || 0;
        sortKey   = sortKey || "cardIndex";
        dir   = (dir) ? dir.substring(7) : "desc"; // Converts from DataTable format "yui-dt-[dir]" to server value "[dir]"
        results   = results || number_per_page_default;
        return "start_index=" + startIndex + "&num_per_page=" + results + "&timestamp=" + new Date().getTime();
    };

    // Called by Browser History Manager to trigger a new state
    var handleHistoryNavigation = function (request) {
        //show the "loading" message.
        cardsDataTable.getTbodyEl().style.display = "none";
        cardsDataTable.showTableMessage(messages["js.loading"]);

        // Sends a new request to the DataSource
        cardsDataSource.sendRequest(request, {
            success:function () {
                //checkCardsAll_btn.set("checked", false); //uncheck all.
                cardsDataTable.getTbodyEl().style.display = "";
                cardsDataTable.hideTableMessage();
                cardsDataTable.onDataReturnSetRows.apply(this, arguments);
            },
            failure:function () {
                //checkCardsAll_btn.set("checked", false); //uncheck all.
                cardsDataTable.getTbodyEl().style.display = "";
                cardsDataTable.hideTableMessage(YAHOO.widget.DataTable.MSG_ERROR);
                cardsDataTable.onDataReturnSetRows.apply(this, arguments);
            },
            scope:cardsDataTable,
            argument:{} // Pass in container for population at runtime via doBeforeLoadData
        });
    };

    // Calculate the first request
    var initialRequest = History.getBookmarkedState("cardTable") || // Passed in via URL
        generateRequest(); // Get default values

    // Register the module
    History.register("cardTable", initialRequest, handleHistoryNavigation);

    // Render the first view
    History.onReady(function () {
        // Current state after BHM is initialized is the source of truth for what state to render
        var currentState = History.getCurrentState("cardTable");
        handleHistoryNavigation(currentState);
    });

    var renderPage = function () {
        var currentState = History.getCurrentState("cardTable") || generateRequest();
        handleHistoryNavigation(currentState);
    };

    var searchPage = function () {
        var currentState =  generateRequest();
        handleHistoryNavigation(currentState);
    };

    // Initialize the Browser History Manager.
    YAHOO.util.History.initialize("yui-history-field", "yui-history-iframe");

    return {
        ds: cardsDataSource,
        dt: cardsDataTable
    };

};

$(function () {
    //initial
    YAHOO.card.paid.generate.init();

    if (!loading) {
        // Initialize the temporary Panel to display while waiting for external content to load
        var loading =
            new YAHOO.widget.Panel("loading",
                { width: "240px",
                    fixedcenter: true,
                    close: false,
                    draggable: false,
                    zindex: 4,
                    modal: true,
                    visible: false
                }
            );

        loading.setHeader("创建中, 请等待...");
        loading.setBody("<img src=\"http://l.yimg.com/a/i/us/per/gr/gp/rel_interstitial_loading.gif\"/>");
        loading.render(document.body);
    }

    var query_btn = new YAHOO.widget.Button("generate_btn", {label:"执行卡片产生任务" });
    var refresh_btn = new YAHOO.widget.Button("refresh_btn", {label:"刷新历史记录" });

    $('#generate_btn').click(function () {

        var quantity = $('#cardQuantity').val();
        var cardValue = $('#cardParValue').val();
        var cardSalePrice = $('#cardSalePrice').val();
        var periodType = $('#cardValidityPeriodType').val();
        var period = $('#cardValidityPeriod').val();
        var deadline = $('#cardActivationDeadline').val();
        var cardType = $('#cardType').val();
        var description = $('#description').val();
        var number = /^[1-9]{1}[0-9]*$/;
        if (!quantity || !number.test(quantity) || quantity>99999) {
            alert("请输入数量，必须为小于99999正整数");
            return false;
        }
        if (!cardValue ||  !number.test(cardValue)) {
            alert("请输入星币值，必须为正整数");
            return false;
        }
        if (!cardSalePrice || !number.test(cardSalePrice)) {
            alert("请输入面值，必须为正整数");
            return false;
        }
        var datePattern = /^(\d{4})([-])(\d{2})([-])(\d{2})/;
        if(!datePattern.test(deadline)){
            alert("日期格式不正确，正确格式为:2013-01-01");
            return false;
        }
        var d = new Date(deadline.replace(/-/g, "/"));
        var n = new Date();
        if (!deadline || d - n < 0) {
            alert("请输入过期时间，且不能小于当前日期");
            return false;
        }
        if (!period || !number.test(period)) {
            alert("请输入有效期限，必须为正整数");
            return false;
        }

        if ($("#paidCardForm").validationEngine('validate')) {
            loading.show();
            $.post('/ozing/card/job/init',
                {
                    cardType: cardType,
                    quantity: quantity,
                    cardValue: cardValue,
                    periodType: periodType,
                    period: period,
                    deadline: deadline,
                    description: description,
                    cardSalePrice: cardSalePrice
                },
                function (data) {
                    loading.hide();
                    //YAHOO.card.paid.generate.init();
                    if (data==true) {
                        window.location.href = "/ozing/card/job";
                    }else if (data==false){
                        alert("今天已经产生99999张卡,达到每日制卡极限.");
                    }
                });
        }
    });

    $('#refresh_btn').click(function(){
        YAHOO.card.paid.generate.init();
    });

    $('#paidCardForm').validationEngine({
        promptPosition:'topRight',
        scroll: false
    });

});